import React, { useEffect, useMemo, useState } from 'react'
import type { MenuProps } from 'antd'
import { Layout, Menu } from 'antd'
import { useLocation, useNavigate } from 'react-router-dom'
import { renderMenuItems } from '@/routes'

const { Sider } = Layout
type MenuItem = Required<MenuProps>['items'][number]

function getItem(label: React.ReactNode, key: React.Key, icon?: React.ReactNode, children?: MenuItem[]): MenuItem {
    return {
        key,
        icon,
        children,
        label
    } as MenuItem
}

// const items: MenuItem[] = [
//     getItem('主页', '/', <HomeOutlined />),
//     getItem('数据管理', 'sub1', <DatabaseOutlined />, [getItem('数据字典', '/cmn/dict')])
// ]

function IndexSider() {
    const navigate = useNavigate()
    const pathname = useLocation().pathname // 获取选中当前路由
    const [collapsed, setCollapsed] = useState<boolean>(false) // 侧边栏收缩状态
    // 映射路由,让路由配置数组与侧边栏关联,使用useMemo缓存数据
    const items: MenuItem[] = useMemo(() => {
        return renderMenuItems().map((item: any) => {
            if (item.children) {
                return getItem(
                    item.label,
                    item.path,
                    item.icon,
                    // 递归二级路由
                    item.children.filter((v: any) => !v.isHide).map((child: any) => getItem(child.label, child.path))
                )
            }
            return getItem(item.label, item.path, item.icon)
        })
    }, [])
    // 解决左侧菜单栏高亮的问题
    // 获取'/'后面的路径
    const path = '/' + pathname.split('/')[1]
    // 将'/'后面的路径与侧边栏的key进行匹配
    const [key, setKey] = useState<string>(path)
    useEffect(() => {
        setKey(path)
    }, [pathname])
    return (
        <Sider breakpoint={'md'} collapsible collapsed={collapsed} onCollapse={(value) => setCollapsed(value)}>
            <div className="logo">
                <img src={require('@/assets/img/logo.png')} alt="" />
                <span style={{ display: collapsed ? 'none' : 'inline-block' }}>尚医通管理系统</span>
            </div>
            <Menu
                onClick={(e) => {
                    navigate(e.key)
                }}
                theme="dark"
                // 默认选中路由,解决高亮问题
                selectedKeys={[pathname]}
                // 默认展开路由
                openKeys={[key]}
                // 展开/关闭的回调
                onOpenChange={(openKeys: string[]) => {
                    setKey(openKeys[1])
                }}
                mode="inline"
                items={items}
            />
        </Sider>
    )
}

export default IndexSider
